
package cz.muni.fi.heathtow.web.pages;

import cz.muni.fi.heathrowapi.AircraftService;
import cz.muni.fi.heathrowapi.HeathrowRoles;
import cz.muni.fi.heathrowapi.dto.AircraftDTO;
import cz.muni.fi.heathtow.web.auth.SecureWicketAuthenticatedWebSession;
import cz.muni.fi.heathtow.web.validation.AircraftBean;
import cz.muni.fi.heathtow.web.validation.UniqueAircraftCodeValidator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormValidatingBehavior;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.apache.wicket.authroles.authorization.strategies.role.metadata.MetaDataRoleAuthorizationStrategy;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.AbstractLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.AbstractItem;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.string.StringValue;
import org.apache.wicket.util.time.Duration;
import org.apache.wicket.validation.validator.RangeValidator;
import org.apache.wicket.validation.validator.StringValidator;

/**
 *
 * @author Jan Richter
 */
public class AircraftView extends MainPage {
    
    @SpringBean(name = "aircraftService")
    private AircraftService aircraftService;

    public static final String PARAM_EDIT = "edit";

    public AircraftView(final PageParameters parameters) {
        super(parameters);
        
        showAll();
        
        StringValue editId = parameters.get(PARAM_EDIT);
        final AircraftDTO editAircraft = editId != null && !editId.isEmpty() ? aircraftService.get(editId.toLongObject()) : new AircraftDTO();

        if (editAircraft.getId() != null) {
            showEditForm(editAircraft).add(new Label("heading", new StringResourceModel("formNameEdit", this, null))).add(new TextField("isEdditing", Model.of("1")));
        } else {
            showEditForm(editAircraft).add(new Label("heading", new StringResourceModel("formNameCreate", this, null))).add(new TextField("isEdditing", Model.of("0")));
        } 

        Component show = new AbstractLink("showForm") {};
        add(show);
        MetaDataRoleAuthorizationStrategy.authorize(show, RENDER, HeathrowRoles.ADMIN);
        
        Label info = new Label("info", new StringResourceModel("info", this, null));
        add(info);
        info.setVisible(SecureWicketAuthenticatedWebSession.get().getRoles().equals(new Roles()));
        
        Component header = new AbstractItem("header");
        add(header);
        MetaDataRoleAuthorizationStrategy.authorize(header, RENDER, HeathrowRoles.USER);
            
    }

    private void showAll() {
        final RepeatingView repeating = new RepeatingView("repeating");
        MetaDataRoleAuthorizationStrategy.authorize(repeating, RENDER, HeathrowRoles.USER);
        add(repeating);

        Label connectionError = new Label("error", new StringResourceModel("error", this, null));
        add(connectionError);
        connectionError.setVisible(false);
        
        try {
            for (final AircraftDTO air : aircraftService.findAll()) {
                AbstractItem item = new AbstractItem(repeating.newChildId());
                item.add(new Label("id", String.valueOf(air.getId())));
                item.add(new Label("code", air.getCode()));
                item.add(new Label("capacity", String.valueOf(air.getCapacity())));
                item.add(new Label("type", air.getType()));
                Link edit = new Link("edit") {
                    @Override
                    public void onClick() {
                        PageParameters parameters = new PageParameters();
                        parameters.add(PARAM_EDIT, air.getId().toString());
                        setResponsePage(AircraftView.class, parameters);

                    }
                };
                MetaDataRoleAuthorizationStrategy.authorize(edit, RENDER, HeathrowRoles.ADMIN);
                item.add(edit);
                
                Link delete = new Link("delete") {
                    @Override
                    public void onClick() {
                        aircraftService.remove(air);
                        setResponsePage(new AircraftView(new PageParameters()));
                    }
                };
                MetaDataRoleAuthorizationStrategy.authorize(delete, RENDER, HeathrowRoles.ADMIN);
                item.add(delete);
                
                repeating.add(item);
            }
        } catch (Exception ex) {
            Logger.getLogger(DestinationView.class.getName()).log(Level.SEVERE, null, ex);
            connectionError.setVisible(!SecureWicketAuthenticatedWebSession.get().getRoles().equals(new Roles()));
        }



    }

    private Form showEditForm(final AircraftDTO aircraft) {
        
        final FeedbackPanel feedback = new FeedbackPanel("feedback");
        feedback.setOutputMarkupId(true);
        add(feedback);
        
        AircraftBean bean= new AircraftBean();
        Form<AircraftBean> form = new Form<AircraftBean>("form", new CompoundPropertyModel<AircraftBean>(bean));
        add(form);
        form.setOutputMarkupId(true);
        
        FormComponent<String> codeField = new RequiredTextField<String>("codeForm", new PropertyModel<String>(aircraft, "code"));
        codeField.add(StringValidator.maximumLength(15));
        codeField.add(new UniqueAircraftCodeValidator(aircraft.getId()));
        codeField.setLabel(new ResourceModel("newCode"));
        
        FormComponent<Integer> capacityField = new RequiredTextField<Integer>("capacityForm", new PropertyModel<Integer>(aircraft, "capacity"));
        capacityField.add(RangeValidator.range(1, 1000));
        capacityField.setLabel(new ResourceModel("newCapacity"));
        
        FormComponent<String> typeField = new RequiredTextField<String>("typeForm", new PropertyModel<String>(aircraft, "type"));
        typeField.add(StringValidator.lengthBetween(1, 50));
        typeField.setLabel(new ResourceModel("newType"));
        
        AjaxButton sumbitButton = new AjaxButton("submitButton") {

            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {            
                if (aircraft.getId() == null) {
                    aircraftService.create(aircraft);
                    setResponsePage(new AircraftView(new PageParameters()));
                } else {
                    aircraftService.update(aircraft);
                    setResponsePage(new AircraftView(new PageParameters()));
                }
            }

            @Override
            protected void onError(AjaxRequestTarget target, Form<?> form) {
                target.add(feedback);
            }
            
        };

        Button cancelButton = new Button("cancelButton") {
            @Override
            public void onSubmit() {
                setResponsePage(new AircraftView(new PageParameters()));
            }
        };
        cancelButton.setDefaultFormProcessing(false); 
        
        form.add(codeField, capacityField, typeField, sumbitButton, cancelButton);
       
        AjaxFormValidatingBehavior.addToAllFormComponents(form, "onkeyup", Duration.ONE_SECOND);
        
        MetaDataRoleAuthorizationStrategy.authorize(form, RENDER, HeathrowRoles.ADMIN);
        
        
        
        return form;
    }
    
}
